﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Semantics;
using GraphBase.UI.WinUI;
using GraphBase.UI;
namespace GraphBase.Presentation
{
    /// <summary>
    /// 所属在GraphBaseWindow下的用户控件
    /// 包括GraphGraphUserControl和GraphBrowserControl
    /// </summary>
    public partial class GraphbaseUserControl : UserControl
    {
        List<Node> GraphNodes;
        List<Node> GridNodes;
        //List<Edge> _edges;
        List<Edge> edges;
        Node node1, node2;

        GraphPositionView PositionView
        {
            get { return graphGraphUserControl1.PositionView; }
            set { graphGraphUserControl1.PositionView = value; }
        }
        Node GraphbaseViewType
        {
            get { return graphGraphUserControl1.GraphbaseViewType; }
        }
        GraphView GraphView
        {
            get { return graphGraphUserControl1.GraphView; }
        }

        public int getColListViewItemSelectedNodeId = -1;
        Node colListViewItemSelected;

        public List<SortedList<int, Node>> ResultList;
        Graph ResultGraph;
        List<Edge> edgeNeighbors;

        #region"参数间的传值"
        GraphBase.IManagedGraphBase _graphdatabase;
        public GraphBase.IManagedGraphBase GraphDatabase
        {
            get { return _graphdatabase; }
            set
            {
                _graphdatabase = value;
                if (value == null)
                {
                    this.toolStrip1.Enabled = false;
                    return;
                }
                if (DesignMode)
                    return;
                this.graphGraphUserControl1.Graph = _graphdatabase;
                //this.graphGraphUserControl1.GraphPositionManager.GraphDatabase = _graphdatabase;
                this.graphBrowserControl2.GraphDatabase = _graphdatabase;
                this.graphBrowserControl2.Initialize(_graphdatabase);
                //this.graphBrowserControl2.NodePropertiesControl.GraphDatabase = _graphdatabase;
                this.graphGridUserControl1.GraphDatabase = _graphdatabase;
                this.graphViewListControl.Initialize((IManagedGraphBase)_graphdatabase);
                _graphdatabase.WarnEvent += new WarningEventHandler(_graphdatabase_WarnEvent);
                this.toolStrip1.Enabled = true;
                this.graphGraphUserControl1.Refresh();
            }
        }

        void _graphdatabase_WarnEvent(IMindObject sender, Warning warning)
        {
            if (warning is GraphBase.GraphDatabase.RecordTooMuchWarning)
            {
                if (MessageBox.Show(this,
                    "记录太多，可能会很慢！是否继续？", "警告", 
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    warning.Cancel = true;
            }
        }
        //跳数，从GraphGraphUserControl传来
        public int Hopdis
        {
            get{return this.HopDistance;}
        }
        int HopDistance
        {
            get { return this.graphGraphUserControl1.HopDistance; }
            set { this.graphGraphUserControl1.HopDistance = value; }
        }
        //枚举
        SearchEngine.EnumSearchManner SearchManner
        {
            get { return this.graphGraphUserControl1.SearchManner; }
            set { this.graphGraphUserControl1.SearchManner = value; }
        }
        #endregion

        //初始化
        public GraphbaseUserControl()
        {
            InitializeComponent();
            //this.SearchManner = SearchEngine.EnumSearchManner.All;
            this.graphGraphUserControl1.SelectedNodeChangedEvent += new GraphGraphUserControl.SelectedNodeChangedEventHandler(graphGraphUserControl1_SelectedNodeChangedEvent);
            this.graphGraphUserControl1.SelectedEdgeChangedEvent+=new GraphGraphUserControl.SelectedEdgeChangedEventHandler(graphGraphUserControl1_SelectedEdgeChangedEvent);
            this.graphViewListControl.OpenViewEvent += new GraphViewListControl.OpenViewEventHandler(this.graphViewListControl_OpenViewEvent);
           
        }

       
        
        private void nodeRel_Paint(object sender, PaintEventArgs e)
        {

        }

        //刷新GraphGrid控件
        public void Refresh_Controls(List<Node> nodes,List<Edge> edges )
        {
            //this.nodes = this.GraphDatabase.QueryNodes();
            //this.edges = this.GraphDatabase.QueryEdges();
            this.graphGridUserControl1.RefreshControls(nodes, edges);
            this.totalNodesToolStripStatusLabel.Text = "节点数：" + nodes.Count;
            this.totalEdgesToolStripStatusLabel.Text = "边数：" + edges.Count;
        }

        public void OpenNodePro(Node node)
        {
            this.graphBrowserControl2.OpenNode(node);
        }

        #region"toolStripButton事件"
        //刷新按钮
        private void Refresh_Click(object sender, EventArgs e)
        {
            try
            {
                //显示控件节点和边
                //if (GridNodes == null)
                this.GraphNodes =  GridNodes = this.GraphDatabase.QueryNodes();
                this.edges = this.GraphDatabase.QueryEdges();
                this.Refresh_Controls(GridNodes, edges);
                if (PositionView != null)
                    PositionView.LoadGraphView(GraphbaseViewType);
                else
                {
                    //准备节点和边
                    this.graphGraphUserControl1.PrepareDrawingGraph(GraphNodes,edges);
                    graphGraphUserControl1.AllNodes = GraphNodes;
                    graphGraphUserControl1.LineEdges = edges;
                }
                //画节点和边
                this.graphGraphUserControl1.Refresh();
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }
        
        //新增节点
        private void newNodeButton_Click(object sender, EventArgs e)
        {
            string nlbl=InputNodeBox.Text.Trim();
            try
            {
                Node node = this.GraphDatabase.AddNode(nlbl);
                this.graphGridUserControl1.ShowNode(node);
                MessageBox.Show("新建" + nlbl + "节点成功！");
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }
        
        //新增边
        private void NewEdgetoolStripButton_Click(object sender, EventArgs e)
        {
            List<Node> nodes = this.GraphDatabase.QueryNodes();
            try
            {
                NewEdgeDialog nedlg = new NewEdgeDialog(this.GraphDatabase, nodes);
                nedlg.ShowDialog();
                if (GridNodes == null)
                    GridNodes = nodes;
                if (edges == null)
                    edges = GraphDatabase.QuerySingleEdge();
                this.Refresh_Controls(GridNodes, edges);
                if (PositionView != null)
                    this.PositionView.LoadGraphView(GraphView);
                else
                {
                    this.graphGraphUserControl1.LineEdges = edges;
                    this.graphGraphUserControl1.PrepareLineAndArcGraph();
                }
                this.graphGraphUserControl1.Refresh();
            }
            catch (Exception exp)
            {
                MessageBox.Show(this, exp.ToString());
            }
        }
        
        //连接节点
        private void connectNodesButton_Click(object sender, EventArgs e)
        {
            List<NodePos> multiplenodes = graphGraphUserControl1.GetSelectedMultipleNodes();
            if(this.graphGridUserControl1.NodesSelectedCount==2)
            //if (this.columnlistView.SelectedItems.Count == 2)
            {                
                //需要获取选中项的节点信息
                foreach (Node node in GridNodes)
                {
                    if (node.Id == this.graphGridUserControl1.NodeSelectedItem[0])
                    {
                        node1 = node;
                    }
                    if (node.Id == this.graphGridUserControl1.NodeSelectedItem[1])
                    {
                        node2 = node;
                    }
                }
                try
                {
                    EdgeDialog dlg = new EdgeDialog(this.GraphDatabase, GridNodes, node1, node2);
                    dlg.ShowDialog();
                    if(edges==null)
                        edges = GraphDatabase.QuerySingleEdge();
                    this.Refresh_Controls(GridNodes, edges);
                    if (PositionView != null)
                        this.PositionView.LoadGraphView(GraphView);
                    else
                    {
                        this.graphGraphUserControl1.LineEdges = edges;
                        this.graphGraphUserControl1.PrepareLineAndArcGraph();
                    }
                    this.graphGraphUserControl1.Refresh();
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }
            }
            else if (multiplenodes.Count == 2)
            {
                foreach (Node node in GridNodes)
                {
                    if (node.FristLeaf.Label == multiplenodes.First<NodePos>().pNode.FristLeaf.Label)
                    {
                        node1 = node;
                    }
                    if (node.FristLeaf.Label == multiplenodes.Last<NodePos>().pNode.FristLeaf.Label)
                    {
                        node2 = node;
                    }
                }
                try
                {
                    EdgeDialog dlg = new EdgeDialog(this.GraphDatabase, GridNodes, node1, node2);
                    dlg.ShowDialog();
                    if (edges == null)
                        edges = GraphDatabase.QuerySingleEdge();
                    this.Refresh_Controls(GridNodes, edges);
                    if (PositionView != null)
                        this.PositionView.LoadGraphView(GraphView);
                    else
                    {
                        this.graphGraphUserControl1.LineEdges = edges;
                        this.graphGraphUserControl1.PrepareLineAndArcGraph();
                    }
                    this.graphGraphUserControl1.Refresh();
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }
            }
            else
            {
                MessageBox.Show("请重新选择两个节点！");
                this.graphGraphUserControl1.Controls.Clear();
                this.graphGraphUserControl1.Refresh();
            }

        }
        
        //根据输入字符串或Id搜索节点
        private void toolStripButtonSearch_Click(object sender, EventArgs e)
        {
            this.graphGridUserControl1.GraphGridClear();
            //this.graphGraphUserControl1.GraphClear();
            string labelorid = this.toolStripTextBoxSearchText.Text.Trim();
            try
            {
                switch (this.SearchManner)
                {
                    case SearchEngine.EnumSearchManner.ByNeightbor:
                        //查找标记为toolStripTextBoxSearchText中内容的节点
                        SearchNeighbor(labelorid);
                        break;
                    case SearchEngine.EnumSearchManner.All:
                    default:
                        int id = -1;
                        try
                        {
                            Int32.Parse(labelorid);
                        }
                        catch
                        {
                        }
                        if (id != -1)
                        {//若输入为Id，则根据Id找
                            Node node = this.GraphDatabase.ResolveNode(id);
                            if (node != null)
                                this.graphGridUserControl1.ShowNode(node);
                            edges.AddRange(this.GraphDatabase.GetEdges(node));
                        }
                        else
                        {
                            //输入为文本，则按标记找
                            //this.nodes = this.GraphDatabase.QueryNodes(labelorid);
                            if (labelorid.IndexOf('%') == -1)
                            {
                                GridNodes = new List<Node>();
                                IList<Node> searchresults = ((IGraph)this.GraphDatabase).GetNodes(labelorid);
                                if (searchresults != null)
                                    GridNodes.AddRange(searchresults);

                                List<Node> gridNodes = this.GraphDatabase.QueryNodesHasText(labelorid);//模糊查询
                                foreach (Node nd in gridNodes)
                                {
                                    if (!GridNodes.Contains(nd))
                                        GridNodes.Add(nd);
                                }
                            }
                        }
                        edges = this.FindEdgesOfGridNodes(GridNodes);

                        //经查询后更新GraphGrid
                        this.Refresh_Controls(GridNodes, edges);
                        //更新GraphGraph
                        
                        GraphNodes = this.FindGraphNodesOfedges(GridNodes, edges);
                        this.graphGraphUserControl1.PrepareDrawingGraph(GraphNodes, edges);
                        graphGraphUserControl1.AllNodes = GraphNodes;
                        graphGraphUserControl1.LineEdges = edges;
                        IList<Node> correctNodes = this.GraphDatabase.GetNodes(labelorid);//精确查询
                        if (correctNodes.Count == 1)
                        {
                            this.graphGraphUserControl1.SelectedNode = correctNodes[0];
                            this.SelectedNodeStatusLabel_SetText("选中节点为：" + correctNodes[0]);
                        }
                        this.graphGraphUserControl1.Refresh();
                        break;
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }
        
        //根据SQL语句搜索节点
        private void toolStripButtonSearchSql_Click(object sender, EventArgs e)
        {
            //this.columnlistView.Items.Clear();
            this.graphGridUserControl1.GraphGridClear();
            string sql = this.toolStripTextBoxSql.Text.Trim();
            if (sql != "")
            {
                List<Node> sqlnodes = null;// this.GraphDatabase.QueryNodesBySql(sql);
                this.graphGridUserControl1.ShowNodes(sqlnodes);
                this.totalNodesToolStripStatusLabel.Text = "节点数：" + sqlnodes.Count;
            }
        }
        
        //删除节点或边        
        private void DeleteButton_Click(object sender, EventArgs e)
        {
            List<NodePos> multiplenodes = this.graphGraphUserControl1.GetSelectedMultipleNodes();
            //删除左侧columnlistView选中的一个节点
            if (this.graphGridUserControl1.NodesSelectedCount == 1)
            {
                int deletenodeid = -1;
                try
                {
                    //deletenode = Convert.ToInt32(columnlistView.SelectedItems[0].Text);
                    deletenodeid = Convert.ToInt32(this.graphGridUserControl1.NodeSelectedItemText[0]);
                    //int.TryParse(columnlistView.SelectedItems[0].Text);
                    GraphDatabase.RemoveNode(GraphDatabase.ResolveNode(deletenodeid));
                    this.graphGraphUserControl1.GraphPositionManager.NodePositions.Remove(deletenodeid);
                    this.Refresh_Controls(graphGraphUserControl1.AllNodes, graphGraphUserControl1.LineEdges);
                    //this.graphGraphUserControl1.PositionView.NodePositions.Remove(deletenode);
                    //画节点和边
                    this.graphGraphUserControl1.Refresh();
                    MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK);
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }
            }
            //删除右侧edgeLV选中的一条边
            else if(this.graphGridUserControl1.EdgesSelectedCount == 1)
            //else if (edgeLV.SelectedItems.Count == 1)
            {
                int deleteedgeid = -1;
                try
                {
                    //deleteedge = Int32.Parse(edgeLV.SelectedItems[0].Text);
                    deleteedgeid = Int32.Parse(this.graphGridUserControl1.EdgeSelecteditemText[0]);
                    Edge deleteedge = this.GraphDatabase.ResolveEdge(deleteedgeid);
                    GraphDatabase.RemoveEdge(deleteedge);
                    this.Refresh_Controls(graphGraphUserControl1.AllNodes, graphGraphUserControl1.LineEdges);
                    if (PositionView != null)
                        this.PositionView.LoadGraphView(GraphView);
                    else
                        this.graphGraphUserControl1.PrepareLineAndArcGraph();
                    this.graphGraphUserControl1.Refresh();
                    MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK);
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }
            }
            //删除图中选中的多个节点
            
            else if (multiplenodes.Count >= 2)
            {
                foreach (NodePos np in multiplenodes)
                {
                    try
                    {
                        GraphDatabase.RemoveNode(np.pNode);
                        this.graphGraphUserControl1.GraphPositionManager.NodePositions.Remove(np.pNode.Id);
                        this.Refresh_Controls(graphGraphUserControl1.AllNodes,graphGraphUserControl1.LineEdges);
                        //this.graphGraphUserControl1.PositionView.NodePositions.Remove(np.pNode.Id);
                        this.graphGraphUserControl1.Refresh();
                        MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK);
                    }
                    catch (Exception exp)
                    {
                        MessageBox.Show(exp.ToString());
                    }
                }
            }
            //删除图中选中的一个节点
            else if (graphGraphUserControl1.GetSelectedNode() != null)
            {
                Node deletenode = graphGraphUserControl1.GetSelectedNode().pNode;
                try
                {
                    GraphDatabase.RemoveNode(deletenode);
                    //画节点和边
                    this.graphGraphUserControl1.GraphPositionManager.NodePositions.Remove(deletenode.Id);
                    this.Refresh_Controls(graphGraphUserControl1.AllNodes, graphGraphUserControl1.LineEdges);
                    this.graphGraphUserControl1.Refresh();
                    MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK);
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }
            }
            //删除图中选中的一条直线边
            else if (graphGraphUserControl1.GetSelectedLine() != null)
            {
                Edge deletelineedge = graphGraphUserControl1.GetSelectedLine().pedge;
                try
                {
                    GraphDatabase.RemoveEdge(deletelineedge);
                    this.Refresh_Controls(graphGraphUserControl1.AllNodes, graphGraphUserControl1.LineEdges);
                    if (PositionView != null)
                        this.PositionView.LoadGraphView(GraphView);
                    else
                        this.graphGraphUserControl1.PrepareLineAndArcGraph();
                    this.graphGraphUserControl1.Refresh();
                    MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK);
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }
            }
            //删除图中选中的圆弧边
            else if (graphGraphUserControl1.GetSelectedArc() != null)
            {
                Edge deletearcedge = graphGraphUserControl1.GetSelectedArc().pedge;
                try
                {
                    GraphDatabase.RemoveEdge(deletearcedge);
                    this.Refresh_Controls(graphGraphUserControl1.AllNodes, graphGraphUserControl1.LineEdges);
                    if (PositionView != null)
                        this.PositionView.LoadGraphView(GraphView);
                    else
                        this.graphGraphUserControl1.PrepareLineAndArcGraph();
                    this.graphGraphUserControl1.Refresh();
                    MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK);
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }
            }
            //else
            //    MessageBox.Show("请重新选择一个节点或一条边！");
        }
        
        //选择节点关联的跳数
        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (toolStripComboBox1.SelectedIndex == 0)
                this.SearchManner = SearchEngine.EnumSearchManner.All;
            else
            {
                this.SearchManner = SearchEngine.EnumSearchManner.ByNeightbor;
                this.HopDistance = toolStripComboBox1.SelectedIndex;
            }
        }

        #region"选项"

        private void ToolStripMenuItem_NodeEdgesNO_Click(object sender, EventArgs e)
        {
            try
            {
                GridNodes = this.GraphDatabase.QueryNodes();
                foreach (Node node in GridNodes)
                {
                    int inedgecount = this.GraphDatabase.GetEdges(node, Edge.EdgeDirection.In).Count;
                    int outedgecount = this.GraphDatabase.GetEdges(node, Edge.EdgeDirection.Out).Count;
                    int alledgecount = this.GraphDatabase.GetEdges(node).Count;
                    //??this.GraphDatabase.UpdateNodeProperties(node, inedgecount, outedgecount, alledgecount);
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        private void ToolStripMenuItem_NodeWeight_Click(object sender, EventArgs e)
        {
            try 
	        {
                GridNodes = this.GraphDatabase.QueryNodes();
                //this.graphGraphUserControl1.GraphPositionManager.UpdateNodeWeight(nodes);
                //string detail = this.graphGraphUserControl1.GraphPositionManager.Nodes
	        }
	        catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        private void graphIONLInputToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GraphBase.IGraphBaseUIForm dlg = (GraphBase.IGraphBaseUIForm)Semantics.Common.ObjectPool.LoadObject("GraphBase.IO.dll", "GraphBase.IO.GraphInputDialog");
            dlg.GraphDatabase = this.GraphDatabase;
            dlg.Show(this);
        }
        #endregion

        #endregion

        #region"状态栏及其他控件事件"

        //用于"根据输入字符串或Id搜索节点"
        void SearchNeighbor(string label)
        {
            List<Node> nodes = this.GraphDatabase.QueryNodesHasText(label);//模糊查询
            
            edges = new List<Edge>();
            GridNodes = new List<Node>();
            GraphNodes=new List<Node>();
            //List<Node> nodes = this.GraphDatabase.QueryNodes(label);
            foreach (Node origin in nodes)
            {
                bool flag = false;
                this.ResultGraph = new Graph();
                this.ResultList = new List<SortedList<int, Node>>();
                SearchEngine engine = new SearchEngine(this.GraphDatabase);
                engine.SearchNodeNeighbor(this.ResultGraph, this.ResultList, this.HopDistance, origin);

                this.ShowNodeNeighbor(ResultGraph, ResultList);
                //this.graphGridUserControl1.ShowEdges(edgeNeighbors);
                foreach (Edge edgeNeighbor in edgeNeighbors)
                {
                    foreach (Edge edge in edges)
                    {
                        if (edge.Id == edgeNeighbor.Id)
                        {
                            flag = true;
                            break;
                        }
                        else
                            flag = false;
                    }
                    if (flag == false)
                        edges.Add(edgeNeighbor);
                }
                //this.graphGraphUserControl1.PrepareDrawingGraph()
            }
            foreach (Node node in ResultGraph.Nodes.Values)
                GridNodes.Add(node);
            this.Refresh_Controls(GridNodes, edges);
            GraphNodes=this.FindGraphNodesOfedges(GridNodes,edges);
            this.graphGraphUserControl1.AllNodes = GraphNodes;
            this.graphGraphUserControl1.LineEdges = edges;

            IList<Node> correctNodes = this.GraphDatabase.GetNodes(label);//精确查询
            if (correctNodes.Count == 1)
            {
                //NodePos selectedNodePos = this.graphGraphUserControl1.NodeConvertToPos(correctNodes[0]);
                this.graphGraphUserControl1.SelectedNode = correctNodes[0];
                this.SelectedNodeStatusLabel_SetText("选中节点为：" + correctNodes[0]);
            }
            //this.graphGridUserControl1.ShowEdges(edges);
            //this.totalNodesToolStripStatusLabel.Text = "节点数：" + ResultGraph.Nodes.Count;
            //this.totalEdgesToolStripStatusLabel.Text = "边数：" + edges.Count;
            //GridNodes = this.FindGraphNodesOfedges(nodes, edges);
            //this.graphGraphUserControl1.PrepareDrawingGraph(GridNodes, edges);
            this.graphGraphUserControl1.Refresh();
        }

        void ShowNodeNeighbor(Graph resultgraph, List<SortedList<int, Node>> neighborNodes)
        {
            edgeNeighbors = new List<Edge>();//
            SortedList<int, Edge> edgeshash = resultgraph.edgesHash;
            foreach (Edge edge in edgeshash.Values)
            {
                edgeNeighbors.Add(edge);
            }
            /*System.Collections.IEnumerator edgeenumerator = resultgraph.edgesHash.GetEnumerator();
            while (edgeenumerator.MoveNext())
            {
                Edge e = (Edge)((System.Collections.DictionaryEntry)edgeenumerator.Current).Label;
                edgeNeighbors.Add(e);
                count++;
            }*/
            this.graphGraphUserControl1.ShowNodeNeighbor(resultgraph, neighborNodes);
            
        }
        bool Flag = false;
        List<Edge> FindEdgesOfGridNodes(List<Node> gridnodes)
        {
            edges = new List<Edge>();
            foreach (Node node in GridNodes)
            {
                IList<Edge> redges = this.GraphDatabase.GetEdges(node);
                foreach (Edge redge in redges)
                {
                    foreach (Edge edge in edges)
                    {
                        if (edge.Id == redge.Id)
                        {
                            Flag = true;
                            break;
                        }
                        else
                            Flag = false;
                    }
                    if (Flag == false)
                        edges.Add(redge);
                }
            }
            return edges;
        }

        List<Node> FindGraphNodesOfedges(List<Node> gridnodes,List<Edge> edges)
        {
            GraphNodes = new List<Node>();
            foreach (Node gridnode in GridNodes)
                GraphNodes.Add(gridnode);
            foreach (Edge edge in edges)
            {
                foreach (Node graphnode in GraphNodes)
                {
                    if (edge.Incoming.Id == graphnode.Id)
                    {
                        Flag = true;
                        break;
                    }
                    else
                        Flag = false;
                }
                if (Flag == false)
                    GraphNodes.Add(edge.Incoming);
                foreach (Node graphnode in GraphNodes)
                {
                    if (edge.Outgoing.Id == graphnode.Id)
                    {
                        Flag = true;
                        break;
                    }
                    else
                        Flag = false;
                }
                if (Flag == false)
                    GraphNodes.Add(edge.Outgoing);
                foreach (Node graphnode in GraphNodes)
                {
                    if (edge.Class.Id == graphnode.Id)
                    {
                        Flag = true;
                        break;
                    }
                    else
                        Flag = false;
                }
                if (Flag == false)
                    GraphNodes.Add(edge.Class);
            }
            return GraphNodes;
        }

        //GraphGrid中选择改变，GraphGraph中的选择也跟着改变
        public void colListViewChanged_graphgraphChanged(int nodeid)
        {
            try
            {
                graphGraphUserControl1.Refresh();
                Node searchselectednode = this.GraphDatabase.ResolveNode(nodeid);
                foreach (NodePos np in this.graphGraphUserControl1.GraphPositionManager.NodePositions.Values)
                {
                    if (np.pNode.Id == searchselectednode.Id)
                    {
                        graphGraphUserControl1.GraphPositionManager.SelectedNodePos = np;
                        graphBrowserControl2.NodePropertiesControl.SelectedNode = np.pNode;
                        graphGraphUserControl1.SearchManner = SearchEngine.EnumSearchManner.ByNeightbor;
                        graphGraphUserControl1.GraphPositionManager.Search(graphGraphUserControl1.HopDistance, np);
                        this.graphBrowserControl2.ShowNode(np.pNode);
                        graphGraphUserControl1.Refresh();
                        break;
                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        //获取GraphGrid中columnlistView被选中的节点
        public Node getColListViewItemSelected()
        {
            colListViewItemSelected = null;
            if (getColListViewItemSelectedNodeId >= 0)
            {
                Node node = this.GraphDatabase.ResolveNode(getColListViewItemSelectedNodeId);
                foreach (NodePos np in this.graphGraphUserControl1.GraphPositionManager.NodePositions.Values)
                {
                    if (np.pNode.Id == node.Id)
                    {
                        graphGraphUserControl1.GraphPositionManager.SelectedNodePos = np;
                        graphBrowserControl2.NodePropertiesControl.SelectedNode = np.pNode;
                        graphGraphUserControl1.SearchManner = SearchEngine.EnumSearchManner.ByNeightbor;
                        graphGraphUserControl1.GraphPositionManager.Search(graphGraphUserControl1.HopDistance, np);
                        colListViewItemSelected = np.pNode;
                        graphGraphUserControl1.Refresh();
                    }
                }
            }
            return colListViewItemSelected;
        }

        //最下方状态栏显示选中节点及选中边
        public void setStatusLabelText()
        {
            this.SelectedNodeStatusLabel.Text = this.graphGridUserControl1.SelectedNodeStatusLabel;
            this.selectedEdgeToolStripStatusLabel.Text = this.graphGridUserControl1.SelectedEdgeStatusLabel;
        }
        //状态栏显示选中节点
        public ToolStripStatusLabel SelectedNodeStatusLabel_SetText(string text)
        {
            this.SelectedNodeStatusLabel.Text = text;
            return SelectedNodeStatusLabel;
        }

        //状态栏显示选中的边
        public ToolStripStatusLabel selectedEdgeToolStripStatusLabel_SetText(string text)
        {
            this.selectedEdgeToolStripStatusLabel.Text = text;
            return selectedEdgeToolStripStatusLabel;
        }

        //状态栏显示节点数
        public ToolStripStatusLabel totalNodesToolStripStatusLabel_SetText(string text)
        {
            this.totalNodesToolStripStatusLabel.Text = text;
            return totalNodesToolStripStatusLabel;
        }

        //状态栏显示边数
        public ToolStripStatusLabel totalEdgesToolStripStatusLabel_SetText(string text)
        {
            this.totalEdgesToolStripStatusLabel.Text = text;
            return totalEdgesToolStripStatusLabel;
        }

        #endregion

        #region"视图相关事件"
        void graphViewListControl_OpenViewEvent(Node viewnode)
        {

            IList<Edge> isedges = this.GraphDatabase.GetEdges(viewnode, Edge.EdgeDirection.Out, this.GraphDatabase.SpecialNodes.IsNode);
            Node viewtype = isedges[0].Incoming;
            if (viewtype.Label == this.GraphDatabase.SpecialNodes.RelationViewNode.Label)
            {
                if (graphViewListControl.contextMenuSelectedItem == 0)
                    this.ShowGraphGraphView(viewnode);
                if (graphViewListControl.contextMenuSelectedItem == 1)
                    this.ShowGraphGridView(viewnode);
                //if (graphViewListControl.contextMenuSelectedItem == 2)
                //this.ShowGraphTableView(viewnode);
            }
            else if (viewtype.Label == this.GraphDatabase.SpecialNodes.TableViewTypeNode.Label)
            {
                if (graphViewListControl.contextMenuSelectedItem == 2)
                    this.ShowGraphTableView(viewnode);
                if (graphViewListControl.contextMenuSelectedItem == 3)
                    this.showGraphTableGrid(viewnode);
                if (graphViewListControl.contextMenuSelectedItem == 4)
                    this.showGraphTableGridByCondition(viewnode);
            }
            else if (viewtype.Label == this.GraphDatabase.SpecialNodes.TreeViewTypeNode.Label)
                this.ShowGraphTreeView(viewnode);
        }
        TabPage page;
        void ShowGraphGraphView(Node viewnode)
        {
            GraphGraphUserControl control = new GraphGraphUserControl();
            control.Graph = this.GraphDatabase;
            control.BackColor = Color.White;
            control.Location = new System.Drawing.Point(3, 3);
            control.Size = new System.Drawing.Size(200, 200);
            control.Dock = DockStyle.Fill;
            control.ShowGraphGraphView(viewnode);
            control.SelectedNodeChangedEvent += new GraphGraphUserControl.SelectedNodeChangedEventHandler(this.graphGraphUserControl1_SelectedNodeChangedEvent);
            page = new TabPage();
            page.Text = viewnode.Label;
            this.tabControl1.TabPages.Add(page);
            page.Controls.Add(control);
            this.tabControl1.SelectedTab = page;
            control.Refresh();
            //page.MouseDoubleClick += new MouseEventHandler(page_MouseDoubleClick);
            tabControl1.MouseDoubleClick+=new MouseEventHandler(tabControl1_MouseDoubleClick);
        }
        
        void ShowGraphGridView(Node viewnode)
        {
            GraphGridUserControl gridcontrol = new GraphGridUserControl();
            gridcontrol.GraphDatabase = this.GraphDatabase;
            gridcontrol.Location = new System.Drawing.Point(3, 3);
            gridcontrol.Size = new System.Drawing.Size(200, 200);
            gridcontrol.Dock = DockStyle.Fill;
            page = new TabPage();
            page.Text = viewnode.Label;
            this.tabControl1.TabPages.Add(page);
            page.Controls.Add(gridcontrol);
            this.tabControl1.SelectedTab = page;
            GraphView gv = graphGridUserControl1.ShowGraphGridView(viewnode);
            List<Edge> edges = new List<Edge>();
            foreach (Edge edge in gv.Edges.Values)
            {
                edges.Add(edge);
            }
            gridcontrol.RefreshControls(gv.Nodes.Values, edges);
            //page.MouseDoubleClick += new MouseEventHandler(page_MouseDoubleClick);
            tabControl1.MouseDoubleClick += new MouseEventHandler(tabControl1_MouseDoubleClick);
        }

        void ShowGraphTableView(Node viewnode)
        {
            GraphTableUserControl tablecontrol = new GraphTableUserControl();
            tablecontrol.GraphDatabase = this.GraphDatabase;
            tablecontrol.Location = new System.Drawing.Point(3, 3);
            tablecontrol.Size = new System.Drawing.Size(200, 200);
            tablecontrol.Dock = DockStyle.Fill;

            tablecontrol.ShowGraphTableView(viewnode);

            page = new TabPage();
            page.Text = viewnode.Label;
            this.tabControl1.TabPages.Add(page);
            page.Controls.Add(tablecontrol);
            this.tabControl1.SelectedTab = page;
            //page.MouseDoubleClick += new MouseEventHandler(page_MouseDoubleClick);
            tabControl1.MouseDoubleClick += new MouseEventHandler(tabControl1_MouseDoubleClick);
        }

        void showGraphTableGrid(Node viewnode)
        {
            GraphTableGridControl tablegridcontrol = new GraphTableGridControl();
            tablegridcontrol.GraphDatabase = this.GraphDatabase;
            tablegridcontrol.Location = new System.Drawing.Point(3, 3);
            tablegridcontrol.Size = new System.Drawing.Size(200, 200);
            tablegridcontrol.Dock = DockStyle.Fill;

            tablegridcontrol.ShowGraphTableGridView(viewnode);

            page = new TabPage();
            page.Text = viewnode.Label;
            this.tabControl1.TabPages.Add(page);
            page.Controls.Add(tablegridcontrol);
            this.tabControl1.SelectedTab = page;
            //page.MouseDoubleClick += new MouseEventHandler(page_MouseDoubleClick);
            tabControl1.MouseDoubleClick += new MouseEventHandler(tabControl1_MouseDoubleClick);
        }

        void showGraphTableGridByCondition(Node viewnode)
        {
            GraphTableGridControl tablegridcontrol = new GraphTableGridControl();
            tablegridcontrol.GraphDatabase = this.GraphDatabase;
            tablegridcontrol.Location = new System.Drawing.Point(3, 3);
            tablegridcontrol.Size = new System.Drawing.Size(200, 200);
            tablegridcontrol.Dock = DockStyle.Fill;

            tablegridcontrol.ShowGraphTableGridViewByCondition(viewnode);

            page = new TabPage();
            page.Text = viewnode.Label;
            this.tabControl1.TabPages.Add(page);
            page.Controls.Add(tablegridcontrol);
            this.tabControl1.SelectedTab = page;
            //page.MouseDoubleClick += new MouseEventHandler(page_MouseDoubleClick);
            tabControl1.MouseDoubleClick += new MouseEventHandler(tabControl1_MouseDoubleClick);
        }

        void ShowGraphTreeView(Node viewnode)
        {
            GraphTreeUserControl treecontrol = new GraphTreeUserControl();
            treecontrol.GraphDatabase = this.GraphDatabase;
            treecontrol.Location = new System.Drawing.Point(3, 3);
            treecontrol.Size = new System.Drawing.Size(200, 200);
            treecontrol.Dock = DockStyle.Fill;
            treecontrol.ShowGraphTreeView(viewnode);

            page = new TabPage();
            page.Text = viewnode.Label;
            this.tabControl1.TabPages.Add(page);
            page.Controls.Add(treecontrol);
            this.tabControl1.SelectedTab = page;

            //page.MouseDoubleClick+=new MouseEventHandler(page_MouseDoubleClick);
            tabControl1.MouseDoubleClick += new MouseEventHandler(tabControl1_MouseDoubleClick);
        }

        //双击移除TabPage
        void page_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            tabControl1.Controls.Remove(page);
        }
        void tabControl1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //page = this.tabControl1.GetChildAtPoint(e.Location);
            //page = this.tabControl1.SelectedTab;
            tabControl1.Controls.Remove(tabControl1.SelectedTab);
        }

        #endregion         

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                IGraphBaseUIForm form = (IGraphBaseUIForm)Semantics.Common.ObjectPool.LoadObject("GraphBase.IO.dll", "GraphBase.IO.InportExport.ImportForm");
                form.GraphDatabase = this.GraphDatabase;
                form.Show(this);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        private void queryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                IGraphBaseUIForm form = (IGraphBaseUIForm)Semantics.Common.ObjectPool.LoadObject("GraphBase.IO.dll", "GraphBase.IO.Query.QueryForm");
                form.GraphDatabase = this.GraphDatabase;
                form.Show(this);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        private void searchByMannerToolStripDropDownButton_Click(object sender, EventArgs e)
        {
            doMannerredSearch(this.searchByMannerToolStripDropDownButton.Text);
        }
        void doMannerredSearch(string text)
        {
            switch (text)
            {
            }
        }

        private void fullMatchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.fullMatchToolStripMenuItem.Checked = true;
            this.searchByMannerToolStripDropDownButton.Text = this.fullMatchToolStripMenuItem.Text;
        }

        private void graphGraphUserControl1_NodeOpenEvent(GraphControlBase sender, Node node)
        {
            this.OpenNodePro(node);
            if (node is IGraph)
            {
                SubGraph.SubGraphForm subfor = new SubGraph.SubGraphForm(this.graphGraphUserControl1 .Graph ,(IGraph)node);
                subfor.Show(this);
            }
        }

        #region GraphGraphUserControl Event Handlers
        void graphGraphUserControl1_SelectedNodeChangedEvent(GraphGraphUserControl sender, NodePos selectednode)
        {
            if (selectednode != null)
                this.graphBrowserControl2.ShowNode(selectednode.pNode);
            this.SelectedNodeStatusLabel_SetText("选中节点为：" + selectednode.pNode);
        }

        void graphGraphUserControl1_SelectedEdgeChangedEvent(GraphGraphUserControl sender, EdgePos selectedline)
        {
            if (selectedline != null)
                this.selectedEdgeToolStripStatusLabel_SetText("选中边为：" + selectedline.pedge.ToString());
        }

        private void graphGraphUserControl1_NodeDeletedEvent(GraphControlBase sender, Node node)
        {

        }

        private void graphGraphUserControl1_EdgeCreatedEvent(GraphControlBase sender, Edge edge)
        {

        }

        private void graphGraphUserControl1_EdgeDeletedEvent(GraphControlBase sender, Edge edge)
        {

        }

        private void graphGraphUserControl1_EdgeEditedEvent(GraphControlBase sender, Edge edge)
        {

        }

        private void graphGraphUserControl1_MultipleNodesDeletedEvent(GraphControlBase sender, ICollection<Node> nodes)
        {

        }

        private void graphGraphUserControl1_NodeLabelChangedEvent(Node changednode)
        {

        }
        #endregion

        private void toolStripSql_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }
        /// <summary>
        /// 是否显示子图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton_ShowSubGraph_Click(object sender, EventArgs e)
        {
            if (this.toolStripButton_ShowSubGraph.Checked)
            {
                this.toolStripButton_ShowSubGraph.Checked = false;
                this.graphGraphUserControl1.ShowSubGraphElement = false;
                this.graphGraphUserControl1.RefreshGraph();
            }
            else
            {
                this.toolStripButton_ShowSubGraph.Checked = true;
                this.graphGraphUserControl1.ShowSubGraphElement = true;
                this.graphGraphUserControl1.RefreshGraph();
            }
        }

        private void graphGraphUserControl1_Load(object sender, EventArgs e)
        {

        }
    }
}
